package com.xindaoapp.happypet.application;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.acra.annotation.ReportsCrashes;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;

import com.baidu.mapapi.SDKInitializer;
import com.iflytek.cloud.SpeechUtility;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.tencent.connect.auth.QQAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.SplashActivity;
import com.xindaoapp.happypet.bean.PostInfo3;
import com.xindaoapp.happypet.db.DBManagerImpl;
import com.xindaoapp.happypet.db.IDBManager;
import com.xindaoapp.happypet.protocol.MoccaApi;
import com.xindaoapp.happypet.protocol.MoccaApiImpl;
import com.xindaoapp.happypet.protocol.PostQueueImpl;
import com.xindaoapp.happypet.protocol.UploaQueueImpl;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.PreferenceFile;
import com.yixia.camera.VCamera;
import com.yixia.camera.demo.service.AssertService;
import com.yixia.camera.util.DeviceUtils;

@ReportsCrashes(formKey = "", // will not be used
        mailTo = "mhjob@163.com", resToastText = R.string.app_name)
public class HappyPetApplication extends Application implements Thread.UncaughtExceptionHandler {
    private MoccaApi mMoccaApi;
    private static HappyPetApplication mIns;

    private IDBManager mIdbManager;
    private boolean isWifiSwitch;

    private UploaQueueImpl mUploaQueueImpl;

    // public LocationClient mLocationClient = null;
    // public BDLocationListener myListener = new MyLocationListener();
    List<Activity> mList = new ArrayList<Activity>();

    public static HappyPetApplication getInstance() {
        return mIns;
    }

    public static final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }

    };
    private SharedPreferences sp;
    private QQAuth mQQAuth;
    // private Tencent mTencent;

    private IWXAPI wxApi;

    @Override
    public void onCreate() {
        super.onCreate();
        SDKInitializer.initialize(getApplicationContext());

        mIns = this;

        // 设置Thread Exception Handler
        // Thread.setDefaultUncaughtExceptionHandler(this);
        // mQQAuth = QQAuth.createInstance(Constants.APPID, this);
        // mTencent = Tencent.createInstance(Constants.APPID, this.getApplicationContext());
        mController = UMServiceFactory.getUMSocialService("com.umeng.login");

        mUploaQueueImpl = new UploaQueueImpl();
        mMoccaApi = new MoccaApiImpl();
        mIdbManager = new DBManagerImpl(this);

        PreferenceFile.init(mIns);
        JPushInterface.setDebugMode(false); // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);

        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(mIns);
        builder.statusBarDrawable = R.drawable.icon;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL; // 设置为自动消失
        builder.notificationDefaults = Notification.DEFAULT_LIGHTS;
        JPushInterface.setPushNotificationBuilder(1, builder);
        Set<String> set = new HashSet<String>();
        set.add("");
        JPushInterface.setTags(mIns, set, null);

        CommonUtil.mkFiledir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/happypet/pic");
        sp = getSharedPreferences("userconfig", MODE_PRIVATE);


        initImageLoader();
        updateLoadImage();

        initPostQueueList();

        // 初始化录像功能
        initRecord();

        initifytek();
    }

    /**
     * 初始化科大讯飞语音输入
     */
    private void initifytek() {
        SpeechUtility.createUtility(getBaseContext(), "appid=" + getString(R.string.app_id));
    }



    private void initRecord() {
        // 设置拍摄视频缓存路径
        File dcim = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (DeviceUtils.isZte()) {
            if (dcim.exists()) {
                VCamera.setVideoCachePath(dcim + "/Camera/VCameraDemo/");
            } else {
                VCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/", "/sdcard-ext/")
                        + "/Camera/VCameraDemo/");
            }
        } else {
            VCamera.setVideoCachePath(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/happypet/VCameraVideo/");
        }
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(true);
        // 初始化拍摄SDK，必须
        VCamera.initialize(this);

        // 解压assert里面的文件
        startService(new Intent(this, AssertService.class));
    }


    public QQAuth getQqAuth() {
        if (mQQAuth == null)
            mQQAuth = QQAuth.createInstance("10021591", this);
        return mQQAuth;
    }

    // public Tencent getTencent() {
    //
    // return mTencent;
    // // return null;
    // }

    public UMSocialService getUMController() {
        return mController;
    }


    public IWXAPI getWxApi() {
        return wxApi;
    }


    public void setWxApi(IWXAPI wxApi) {
        this.wxApi = wxApi;
    }


    private void initPostQueueList() {
        // if (UserState.isLogged()) {
        // 初始化下载队列
        List<PostInfo3> list = HappyPetApplication.get().getDBManager().loadPosts();
        for (int i = 0; i < list.size(); i++) {
            HappyPetApplication.get().getUploaQueueImpl()
                    .addQueue(new PostQueueImpl(this, UserState.getUserUid(), list.get(i)));
        }
        // }
    }

    public void updateLoadImage() {
        boolean isWifiOnOff = sp.getBoolean("wifi", true);
        int available = CommonUtil.isNetworkAvailable(this);
        if (available == 1) {
            CommonParameter.isLoadImg = true;
        } else {
            if (isWifiOnOff) {
                if (CommonUtil.isNetworkAvailable(getApplicationContext()) == 1) {
                    CommonParameter.isLoadImg = true;
                } else {
                    CommonParameter.isLoadImg = true;// 控制非wifi也可以加载图片
                }
            } else {
                CommonParameter.isLoadImg = true;
            }
        }
    }

    public UploaQueueImpl getUploaQueueImpl() {
        return mUploaQueueImpl;
    }

    public boolean getIsSwitch() {
        return isWifiSwitch;
    }

    public static HappyPetApplication get() {
        return mIns;
    }

    public IDBManager getDBManager() {
        return mIdbManager;
    }

    public MoccaApi getMoccaApi() {
        return mMoccaApi;
    }

    protected void initImageLoader() {
        DisplayImageOptions defaultOptions =
                new DisplayImageOptions.Builder()
                        .resetViewBeforeLoading(true)
                        .imageScaleType(ImageScaleType.NONE)
                        // .displayer(new FadeInBitmapDisplayer(1000))
                        .bitmapConfig(Bitmap.Config.RGB_565)
                        .showImageForEmptyUri(R.drawable.picture_loading)
                        .showImageOnFail(R.drawable.picture_loading)
                        .showStubImage(R.drawable.picture_loading).cacheInMemory(true) // 关闭掉?
                        .imageScaleType(ImageScaleType.IN_SAMPLE_INT)// 新添加的
                        .cacheOnDisc(true).build();

        ImageLoaderConfiguration config =
                new ImageLoaderConfiguration.Builder(getApplicationContext())
                        .memoryCache(new WeakMemoryCache())
                        // 新添加的-WeakMemoryCache
                        // .memoryCacheExtraOptions(480, 800)
                        // // default = device screen dimensions
                        // .discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75, null)
                        .denyCacheImageMultipleSizesInMemory().discCacheSize(100 * 1024 * 1024)
                        .defaultDisplayImageOptions(defaultOptions)
                        .memoryCacheSize(20 * 1024 * 1024)
                        .discCacheFileCount(500)
                        // .memoryCache(new LruMemoryCache(2 * 1024 * 1024))//去掉这个,跟新添加的有冲突
                        .tasksProcessingOrder(QueueProcessingType.LIFO)
                        .memoryCacheSizePercentage(20)
                        // 缓存一百张图片
                        .memoryCacheExtraOptions(240, 320).threadPoolSize(3)
                        // .imageDecoder(new BaseImageDecoder())
                        .threadPriority(Thread.NORM_PRIORITY - 2)
                        // .discCacheExtraOptions(240, 320, CompressFormat.JPEG, 80, null)
                        .imageDownloader(new BaseImageDownloader(mIns, 20 * 1000, 60 * 1000))
                        .build();// .discCacheExtraOptions(240, 320, CompressFormat.JPEG, 50, null)
        ImageLoader.getInstance().init(config);
    }

    public double lat;
    public double lng;
    public String address;
    private UMSocialService mController;

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        ImageLoader.getInstance().clearMemoryCache();
        System.gc();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // System.out.println("uncaughtException");
        // System.exit(0);
        // Intent intent = new Intent(this, SplashActivity.class);
        // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        // startActivity(intent);

        // try {
        // Thread.sleep(500);
        // } catch (InterruptedException e) {
        // Log.e("tag", "error : ", e);
        // }
        // Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
        // PendingIntent restartIntent =
        // PendingIntent.getActivity(getApplicationContext(), 0, intent,
        // Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        // // 退出程序
        // AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        // mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
        // // 杀死该应用进程
        // android.os.Process.killProcess(android.os.Process.myPid());

        restartApp();
    }

    public void restartApp() {
        // System.exit(0);
        // finishActivity();
        Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);


        // Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
        // PendingIntent restartIntent =
        // PendingIntent.getActivity(getApplicationContext(), 0, intent,
        // Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        // // 退出程序
        // AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        // mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent);

        android.os.Process.killProcess(android.os.Process.myPid()); // 结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
    }

    /**
     * 向Activity列表中添加Activity对象
     */
    public void addActivity(Activity a) {
        mList.add(a);
    }

    /**
     * 关闭Activity列表中的所有Activity
     */
    public void finishActivity() {
        for (Activity activity : mList) {
            if (null != activity) {
                activity.finish();
            }
        }
    }


}
